package com.example.medicalrecord.AggregationModule.medicine.service.impl;

import com.example.medicalrecord.AggregationModule.medicine.mapper.MedicineMapper;
import com.example.medicalrecord.AggregationModule.medicine.pojo.dto.MedicineParam;
import com.example.medicalrecord.AggregationModule.medicine.pojo.dto.MedicineQuery;
import com.example.medicalrecord.AggregationModule.medicine.pojo.entity.Medicine;
import com.example.medicalrecord.AggregationModule.medicine.pojo.vo.MedicineVO;
import com.example.medicalrecord.AggregationModule.medicine.service.MedicineService;
import com.example.medicalrecord.AggregationModule.medicineOption.mapper.MedicineOptionMapper;
import com.example.medicalrecord.base.response.PageData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class MedicineServiceImpl implements MedicineService {
    @Autowired
    MedicineMapper medicineMapper;
    @Autowired
    MedicineOptionMapper medicineOptionMapper;

    @Override
    public PageData selectMedicine(MedicineQuery medicineQuery) {
        log.debug("查询药品类业务:medicineQuery={}",medicineQuery);
        List<MedicineVO> medicineVOList = medicineMapper.selectMedicine(medicineQuery);
        //准备PageData对象用来装返回给前端的数据
        PageData pageData = new PageData();
        //向PageData对象中装存入当前页药品类数据
        pageData.setList(medicineVOList);
        //向PageData对象中装存入总记录数
        pageData.setTotal(medicineMapper.selectMedicineCount(medicineQuery));
        return pageData;
    }

    @Override
    public void saveMedicine(MedicineParam medicineParam) {
        log.debug("保存药品类业务:medicineParam={}",medicineParam);
        Medicine medicine = new Medicine();
        BeanUtils.copyProperties(medicineParam,medicine);
//        判断id是否为空,id为空代表新增数据,id不为空代表更新数据
        if (medicine.getId() == null){
            medicine.setCreateTime(new Date());
            medicineMapper.insert(medicine);
        }else {
            medicine.setUpdateTime(new Date());
            medicineMapper.update(medicine);
        }

    }

    @Override
    public void deleteMedicine(Long medicineId) {
        log.debug("删除药品类业务:medicineId={}",medicineId);
        medicineOptionMapper.deleteByMedicineId(medicineId);
        medicineMapper.delete(medicineId);
    }
}
